package com.linxi.handy.component.list;

import com.linxi.handy.component.control.HomeControl;
import com.linxi.handy.component.listener.DatabaseList;
import com.linxi.handy.util.ConnectionUtils;

import javax.swing.*;
import javax.swing.tree.TreeNode;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @author user
 */
public class MouseProcessListener implements MouseListener {
    @Override
    public void mouseClicked(MouseEvent arg0) {
        if (arg0.getButton() != MouseEvent.BUTTON1) {
            return;
        }
        String sql = "drop ";
        TreeNode s = (TreeNode) DatabaseList.tree.getLastSelectedPathComponent();
        if (s == null) {
            return;
        }
        int n = JOptionPane.showConfirmDialog(null, "确认删除" + s + "吗?", "删除", JOptionPane.YES_NO_OPTION);
        if (n != JOptionPane.YES_OPTION) {
            return;
        }
        //是叶子
        if (s.getParent() != DatabaseList.top) {
            sql = sql + "table " + s.getParent().toString() + "." + s;

        } else {
            sql = sql + "database " + s;
        }

        String error = null;
        try {
            Statement stmt = ConnectionUtils.conn.createStatement();
            stmt.executeUpdate(sql);
            stmt.close();
        } catch (SQLException e1) {
            error = e1.getMessage();
            e1.printStackTrace();
        }

        HomeControl.fdi.setText(sql, error);

        //删除某个数据库，或数据表后，打开的页面应关闭 是叶子
        if (s.getParent() != DatabaseList.top) {
            int j = HomeControl.ft.indexOfTab(s.getParent().toString() + "." + s);
            //删除打开的表格
            if (j > -1) {
                HomeControl.ft.remove(j);
            }
        } else {
            int count = s.getChildCount();
            for (int i = 0; i < count; i++) {
                int j = HomeControl.ft.indexOfTab(s + "." + s.getChildAt(i).toString());
                //刷新打开的表格
                if (j > -1) {
                    HomeControl.ft.remove(j);
                }
            }
        }
        //刷新列表
        DatabaseList.addTree();
    }

    @Override
    public void mouseEntered(MouseEvent arg0) {

    }

    @Override
    public void mouseExited(MouseEvent arg0) {

    }

    @Override
    public void mousePressed(MouseEvent arg0) {

    }

    @Override
    public void mouseReleased(MouseEvent arg0) {

    }
}
